package com.itic.mall.mobile.jd;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpu;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample;
import com.itic.mall.system.goods.goodsspu.service.GoodsSpuService;
import com.itic.mall.system.market.marketadvert.persistence.model.MarketAdvert;
import com.itic.mall.system.market.marketadvert.persistence.model.MarketAdvertExample;
import com.itic.mall.system.market.marketadvert.service.MarketAdvertService;
import com.itic.mall.system.market.marketarrondi.service.MarketArrondiService;
import com.itic.mall.system.market.marketspecial.persistence.model.MarketSpecial;
import com.itic.mall.system.market.marketspecial.persistence.model.MarketSpecialExample;
import com.itic.mall.system.market.marketspecial.service.MarketSpecialService;
import com.itic.mall.system.share.sharehistory.persistence.model.ShareHistory;
import com.itic.mall.system.share.sharehistory.service.ShareHistoryService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;

/**
 * 京东接口
 * 
 * @author 王文鑫
 * @date 2017年12月22日 上午10:33:24
 */
@Controller
@RequestMapping(value = "/mobile/jd")
public class JdInterface extends BaseMobileInterface {

	// 返回属性黑名单
	private static String[] ignoreProperties = new String[] { "createUser", "isEffective", "updateTime", "note",
			"createTime", "orgCode" };

	@Autowired
	protected MarketArrondiService marketArrondiService;

	@Autowired
	private MarketAdvertService marketAdvertService;

	@Autowired
	private MarketSpecialService marketSpecialService;
	
	@Autowired
	private GoodsSpuService goodsSpuService;
	
	@Autowired
	private ShareHistoryService shareHistoryService;
	  /**
	    *测试
	    * @return
	    */
	   @RequestMapping(value="/test")
	   @ResponseBody
	   public Map<String,Object> test( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		JSONArray queryProductList = null;// JdCouponUtils.queryProductList(1, 1);
		   		resultMap.put(DATA,queryProductList);
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("JdInterface", "test", e.toString(),"京东test",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	  /**
	    * APP京东一级分类搜索
	    * @return
	    */
	   @RequestMapping(value="/categorys")
	   @ResponseBody
	   public Map<String,Object> categorys( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		
		   		resultMap.put(DATA, getTopCategorysByType("jd"));
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("goodsCategoryService", "categorys", e.toString(),"APP首页大分类搜索",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }

	/**
	 * 京东展示页轮播图信息
	 * 
	 * @author 王文鑫
	 * @date 2017年12月22日 上午11:50:49
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/banners")
	@ResponseBody
	public Map<String, Object> banners(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			// 首页轮播图信息
			resultMap.put(DATA, getMarketBannersByType("jd"));
			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("IndexInterface", "banners", e.toString(), "京东展示页轮播图信息", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}

	/**
	 * 京东展示页轮播图信息
	 * 
	 * @author 王文鑫
	 * @date 2017年12月22日 上午11:50:39
	 * @param MarketArrondiInterface
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/models")
	@ResponseBody
	public Map<String, Object> models(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			// 首页轮播图信息
			resultMap.put(DATA, getMarketActivitysByType("jd"));
			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("JdInterface", "models", e.toString(), "京东八大模块", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}


	/**
	 * 获取广告位
	 * 
	 * @author 许小宝
	 * @date 2017年12月22日 下午3:31:52
	 * @param request
	 * @param response
	 * @param address
	 * @return
	 */
	@RequestMapping(value = "/adverts")
	@ResponseBody
	public Map<String, Object> adverts(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String errorCode = PARAM_ERROR_CODE; // 缺少必填参数
		String errorMsg = PARAM_ERROR_MSG;// 缺少必填参数，返回信息

		try {
			resultMap.put(DATA, getMarketAdvertByTypeAndAddress("jd","one"));
			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			// 服务器异常处理
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			// 打印异常日志
			logException("YhInterface", "advert", e.toString(), "获取广告位", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response); // 跨域处理
		return resultMap;
	}
	
	/**
	 * 获取特卖时间
	 * @author 王文鑫
	 * @date 2017年12月25日 上午11:21:42
	 * @param request
	 * @param response
	 * @return
	 */
	   @RequestMapping(value="/getspecialtime")
	   @ResponseBody
	   public Map<String,Object> getspecialtime( HttpServletRequest request,HttpServletResponse response){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		MarketSpecialExample example = new MarketSpecialExample();
		   		
		   		example.setOrderByClause("SPECIAL_TIME ASC"); //特卖时间排序
		   		com.itic.mall.system.market.marketspecial.persistence.model.MarketSpecialExample.Criteria criteria = example.createCriteria();
		   		
		   		criteria.andSpuPlatformEqualTo("002"); //002  京东分类
		   		
		   		List<MarketSpecial> list = marketSpecialService.list(example);
		   		List<MarketSpecial> list1 = new ArrayList<MarketSpecial>();
		   		Date nowtime = new Date(); //当前时间
		   		Date specialtime = null; //特卖时间
		   		int flag = 0 ; 
		   		
		   		for (int i = 0; i < list.size(); i++) {
		   			specialtime = list.get(i).getSpecialTime(); //获取特卖时间
		   			//判断距离最近已开始的特卖时间
		   			if(DateHelper.isGreaterDate(nowtime,specialtime)){
		   				flag = i;
		   			}
		   			//最后一下循环结束
		   			if((i+1)==list.size()){
		   				if(flag!=0 && (flag+1)!=list.size()){
			   				list.get(flag).setNowTime(nowtime); //设置当前时间
			   				list.get(flag).setNextTime(list.get(flag+1).getSpecialTime());//设置下一次特卖时间
			   				list.get(flag).setNextId(list.get(flag+1).getId());//设置下一次特卖id
			   				list1.add(list.get(flag)); //添加返回list
			   			}else{
			   				list.get(flag).setNowTime(nowtime); //设置当前时间
			   				list1.add(list.get(flag)); //添加返回list
			   			}
		   			}
				}
		   		
		   		resultMap.put(DATA, ValueHelper.tranList2MapList(list1, new String[] { "note","reorder","categoryCode","createUser", "isEffective", "updateTime", "orgCode","isVisible","createTime"}));
		   		errorCode = SUCCESS_ERROR_CODE;
		       	errorMsg = SUCCESS_ERROR_MSG;
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("marketSpecialService", "getspecialtime", e.toString(),"获取特卖时间",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	

	/**
	 * 查询京东特卖商品
	 * @author 王文鑫
	 * @date 2017年12月25日 上午10:45:08
	 * @param request
	 * @param response
	 * @param type
	 * @param keyword
	 * @param categoryId
	 * @param orderType
	 * @return
	 */
	@RequestMapping(value = "/speciallist")
	@ResponseBody
	public Map<String, Object> speciallist(HttpServletRequest request, HttpServletResponse response, String type,
			String keyword, String specialId, String orderType) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			Map<String, Object> dataMap = new HashMap<String, Object>();

			GoodsSpuExample example = new GoodsSpuExample();
			if (StringHelper.isNotBlank(orderType)) {
				if ("priceDesc".equals(orderType)) {
					example.setOrderByClause("PRICE DESC");
				}
				if ("priceAsc".equals(orderType)) {
					example.setOrderByClause("PRICE ASC");
				}
				if ("commisionDesc".equals(orderType)) {
					example.setOrderByClause("MARKET_PROFIT ASC");
				}
				if ("commisionAsc".equals(orderType)) {
					example.setOrderByClause("MARKET_PROFIT ASC");
				}
			} else {
				example.setOrderByClause("CREATE_TIME DESC");
			}

			com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample.Criteria criteria = example
					.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);// 是否有效
			criteria.andIsShowEqualTo(DBConst.TRUE);// 是否可见

			criteria.andIsSpecialEqualTo("1"); // 是否特卖

			//查询条件特卖id
			criteria.andSpecialIdEqualTo(specialId);
			
			criteria.andSpuPlatformEqualTo(type);

			this.handlePageQueryDefault(request, example);// 分页
			int count = goodsSpuService.count(example);// 总条数
			List<GoodsSpu> list = goodsSpuService.list(example);// 数据list

			dataMap.put("total", count);
			dataMap.put("isMore", isMore(request, count));
			dataMap.put("list",ValueHelper.tranList2MapList(list,spuIgnoreProperties));
			resultMap.put(DATA, dataMap);

			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("goodsSpuService", "speciallist", e.toString(), "特卖商品list", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	/**
	 * 查询京东爆款产品
	 * 
	 * @author 王文鑫
	 * @date 2017年12月22日 下午6:21:59
	 * @param request
	 * @param response
	 * @param type
	 * @param keyword
	 * @param categoryId
	 * @param orderType
	 * @return
	 */
	@RequestMapping(value = "/hotlist")
	@ResponseBody
	public Map<String, Object> hotlist(HttpServletRequest request, HttpServletResponse response, String type,
			String keyword, String categoryId, String orderType) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			Map<String, Object> dataMap = new HashMap<String, Object>();

			GoodsSpuExample example = new GoodsSpuExample();
			if (StringHelper.isNotBlank(orderType)) {
				if ("priceDesc".equals(orderType)) {
					example.setOrderByClause("PRICE DESC");
				}
				if ("priceAsc".equals(orderType)) {
					example.setOrderByClause("PRICE ASC");
				}
				if ("commisionDesc".equals(orderType)) {
					example.setOrderByClause("MARKET_PROFIT ASC");
				}
				if ("commisionAsc".equals(orderType)) {
					example.setOrderByClause("MARKET_PROFIT ASC");
				}
			} else {
				example.setOrderByClause("CREATE_TIME DESC");
			}

			com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample.Criteria criteria = example
					.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);// 是否有效
			criteria.andIsShowEqualTo(DBConst.TRUE);// 是否可见

			criteria.andIsHotEqualTo("1");

			criteria.andSpuPlatformEqualTo(type);

			this.handlePageQueryDefault(request, example);// 分页
			int count = goodsSpuService.count(example);// 总条数
			List<GoodsSpu> list = goodsSpuService.list(example);// 数据list

			dataMap.put("total", count);
			dataMap.put("isMore", isMore(request, count));
			dataMap.put("list",
					ValueHelper.tranList2MapList(list,spuIgnoreProperties));
			resultMap.put(DATA, dataMap);

			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("goodsSpuService", "hotlist", e.toString(), "查询京东爆款产品", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}

	/**
	 * 查询京东精品商品
	 * 
	 * @author 王文鑫
	 * @date 2017年12月22日 下午7:20:17
	 * @param request
	 * @param response
	 * @param type
	 * @param keyword
	 * @param categoryId
	 * @param orderType
	 * @return
	 */
	@RequestMapping(value = "/jplist")
	@ResponseBody
	public Map<String, Object> jplist(HttpServletRequest request, HttpServletResponse response, String type,
			String keyword, String categoryId, String orderType) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			Map<String, Object> dataMap = new HashMap<String, Object>();

			GoodsSpuExample example = new GoodsSpuExample();
			if (StringHelper.isNotBlank(orderType)) {
				if ("priceDesc".equals(orderType)) {
					example.setOrderByClause("PRICE DESC");
				}
				if ("priceAsc".equals(orderType)) {
					example.setOrderByClause("PRICE ASC");
				}
				if ("commisionDesc".equals(orderType)) {
					example.setOrderByClause("MARKET_PROFIT ASC");
				}
				if ("commisionAsc".equals(orderType)) {
					example.setOrderByClause("MARKET_PROFIT ASC");
				}
			} else {
				example.setOrderByClause("CREATE_TIME DESC");
			}

			com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpuExample.Criteria criteria = example
					.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);// 是否有效
			criteria.andIsShowEqualTo(DBConst.TRUE);// 是否可见

			criteria.andIsJingpingEqualTo("1");

			criteria.andSpuPlatformEqualTo(type);
		
			this.handlePageQueryDefault(request, example);// 分页
			int count = goodsSpuService.count(example);// 总条数
			List<GoodsSpu> list = goodsSpuService.list(example);// 数据list

			dataMap.put("total", count);
			dataMap.put("isMore", isMore(request, count));
			dataMap.put("list",
					ValueHelper.tranList2MapList(list,spuIgnoreProperties));
			resultMap.put(DATA, dataMap);

			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("goodsSpuService", "jplist", e.toString(), "查询京东精品商品", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}


	/**
	 * 获取广告位1
	 * 
	 * @author 王文鑫
	 * @date 2017年12月22日 下午3:31:52
	 * @param request
	 * @param response
	 * @param address
	 * @return
	 */
	@RequestMapping(value = "/detailadvert")
	@ResponseBody
	public Map<String, Object> detailadvert(HttpServletRequest request, HttpServletResponse response,
			String address) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String errorCode = PARAM_ERROR_CODE; // 缺少必填参数
		String errorMsg = PARAM_ERROR_MSG;// 缺少必填参数，返回信息

		try {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			MarketAdvertExample example = new MarketAdvertExample();
			example.setOrderByClause("REORDER ASC");
			com.itic.mall.system.market.marketadvert.persistence.model.MarketAdvertExample.Criteria criteria = example
					.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andIsVisibleEqualTo(DBConst.TRUE);

			Date date = new Date();
			criteria.andStartTimeLessThan(date);
			criteria.andEndTimeGreaterThan(date);
			criteria.andAddressEqualTo(address);

			this.handlePageQueryDefault(request, example);// 分页
			List<MarketAdvert> list = marketAdvertService.list(example);

			dataMap.put("list", ValueHelper.tranList2MapList(list, ignoreProperties));

			resultMap.put(DATA, dataMap);

			// 请求成功
			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			// 服务器异常处理
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			// 打印异常日志
			logException("marketAdvertService", "advert", e.toString(), "获取广告位1", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response); // 跨域处理
		return resultMap;
	}
	
	/**
     * 联盟微信手q通过subUnionId获取推广链接
     * @author 王文鑫
     * @date 2017年12月27日 下午2:36:50
     * @param request
     * @param response
     * @return
    
   @RequestMapping(value="/syncJdSpreadUrl")
   @ResponseBody
   public Map<String,Object> syncJdSpreadUrl( HttpServletRequest request,HttpServletResponse response,String spuId,String appId ,String token){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	String goods_url = null;
	   	try{
	   		
	   		if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(spuId) ){
	   			UsersMall usersMall =  this.getUsersByTokenAndAppId(token, appId);
	   			if(null != usersMall){
	   				//根据UserId获取推广位链接id
	   				String tgw_id = usersCodeService.getTgwIdByUserId(usersMall.getId());
	   				//根据spuId 获取 skuId
	   				String skuId = goodsSpuService.getSkuIdBySpuId(spuId);
	   				
	   				Jdset jdset = getJdset();
	   		   		JdClient client=new DefaultJdClient(jdset.getApiUrl(),jdset.getAccessToken(),jdset.getJdKey(),jdset.getJdSecret()); 
	   		   		ServicePromotionWxsqGetCodeBySubUnionIdRequest requestJd = new ServicePromotionWxsqGetCodeBySubUnionIdRequest();
	   				
	   				//判断skuId 是否存在
	   				if(StringHelper.isNotBlank(skuId)){
	   					
	   					requestJd.setMaterialIds(skuId); //	推广物料：单品skuId
		   		   		requestJd.setProCont( 1 ); //推广内容：1单品
		   		   		requestJd.setSubUnionId( jdset.getUnionId() ); //子联盟ID
		   		   		
		   		   		//判断推广位链接是否存在
		   		   		if(StringHelper.isNotBlank(tgw_id)){
		   		   			requestJd.setPositionId( StringHelper.toLong(tgw_id) ); //	推广位ID
		   		   		}
		   		   		//发送京东请求
		   		   		ServicePromotionWxsqGetCodeBySubUnionIdResponse responseJd=client.execute(requestJd);
		   		   		//判断是否成功
		   		   		if( "0".equals(responseJd.getCode()) ){
		   		   			String result2 = responseJd.getGetcodebysubunionidResult();
		   		   			if( result2.contains("urlList") ){
		   		   				JSONObject jsonArray = JSONObject.fromObject(result2);
		   		   		        String urlList = jsonArray.get("urlList").toString();
		   		   		        jsonArray = JSONObject.fromObject(urlList);
		   		   		        goods_url = jsonArray.get(skuId).toString();
		   		   		        
		   		   		        resultMap.put(DATA, goods_url);
		   		   			}
			   		   		errorCode = SUCCESS_ERROR_CODE;
			   		       	errorMsg = SUCCESS_ERROR_MSG;
		   		   		}else{
		   		   		 errorCode = SERVER_ERROR_CODE; //服务器错误
	   				   	 errorMsg = SERVER_ERROR_MSG;
		   		   		}
	   				}else{
	   					 errorCode = PARAM_ERROR_CODE;
	   				   	 errorMsg = PARAM_ERROR_MSG;
	   				}
	   			}else{
	   				errorCode = OBJECT_NULL_ERROR_MSG; //获取对象错误
		   		   	errorMsg = OBJECT_ERROR_MSG;
	   			}
	   		}else{
	   			 errorCode = PARAM_ERROR_CODE; //缺少必要参数
	   		   	 errorMsg = PARAM_ERROR_MSG;
	   		}
	   	}catch(Exception e){
	   		errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("ProjectInterface", "syncJdSpreadUrl", e.toString(),"联盟微信手q通过subUnionId获取推广链接",e);
	   	}
	   	resultMap.put(CODE, errorCode);
	   	resultMap.put(MSG, errorMsg);
	   	isCrrossDomain(response);
	   	return resultMap;
   }
 */
   /**
    * 联盟微信手q通过subUnionId获取推广链接
    * @author 许小宝
    * @date 2017年12月27日 下午2:36:50
    * @param request
    * @param response
    * @return
    */
  @RequestMapping(value="/getUrl")
  @ResponseBody
  public Map<String,Object> getUrl( HttpServletRequest request,HttpServletResponse response,String spuId,String appId ,String token){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		if( StringHelper.isNotBlank(spuId) ){
	   			 GoodsSpu goodsSpu = goodsSpuService.get(spuId);
	   			 //判断商品是否有效
  				 if( null != goodsSpu ){
  					    //添加点击统计
   					    addClick(goodsSpu);
	  					UsersMall user =  this.getUsersByTokenAndAppId(token, appId);
	  					//判断用户是否登入，用户未登入也可以进入详情
	  		   			if( null != user ){
	  		   			     List<ShareHistory> listHistorys = shareHistoryService.listBySpuIdAndUserId(spuId, user.getId());
			   				 if( listHistorys.size()>0 ){
			   					ShareHistory shareHistory = listHistorys.get(0); 
			   				   //还是要实时的获取京东的优惠券信息
								String link = "";
								if( StringHelper.isNotBlank(shareHistory.getCommonUrl()) ){
									link = shareHistory.getCommonUrl();
								}else{
									//生成二合一链接，更新数据库
									//生成优惠券的二合一链接，更新数据库
									String tempLink = goodsSpuService.getCommonErheyiLink(spuId,user.getId());
									if( StringHelper.isNotBlank(tempLink) ){
										link = tempLink;
										shareHistory.setCommonUrl(link);
										shareHistoryService.edit(shareHistory);
									}
								}
								resultMap.put(DATA, link);
								errorCode = SUCCESS_ERROR_CODE;
								errorMsg = SUCCESS_ERROR_MSG;
			   				 }else{
			   				    //添加一个分享记录
			   					String historyId = IdGen.uuid();
			   					String commonUrl = goodsSpuService.getCommonErheyiLink(spuId,user.getId());
			   					ShareHistory shareHistory = new ShareHistory();
			   					if( StringHelper.isNotBlank(commonUrl) ){
			   						shareHistory.setCommonUrl( commonUrl );
			   					}
			   					shareHistory.setId(historyId);
			   					shareHistory.setUserId(user.getId());
			   					shareHistory.setReorder(0);
			   					shareHistory.setSpuId(goodsSpu.getId());
			   					shareHistoryService.add(shareHistory);
			   					
			   					resultMap.put(DATA, commonUrl);
								errorCode = SUCCESS_ERROR_CODE;
								errorMsg = SUCCESS_ERROR_MSG;
			   				 }
	  				 }else{
	  					 String commonLinkByDdt = goodsSpuService.getCommonLinkByDdt(goodsSpu.getSkuId(), null);
	  					 if( StringHelper.isNotBlank(commonLinkByDdt) ){
	  						resultMap.put(DATA, commonLinkByDdt);
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
	  					 }else{
	  						 //商品无效了,可以删除
	  						goodsSpuService.delete(goodsSpu);
	  						errorCode = LINK_NULL_ERROR_CODE;
							errorMsg = LINK_NULL_ERROR_MSG;
	  					 }
	  				 }
	   			}else{
	   				errorCode = LINK_NULL_ERROR_CODE;
					errorMsg = LINK_NULL_ERROR_MSG;
	   			}
	   		}
	   	}catch(Exception e){
	   		errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("ProjectInterface", "syncJdSpreadUrl", e.toString(),"联盟微信手q通过subUnionId获取推广链接",e);
	   	}
	   	resultMap.put(CODE, errorCode);
	   	resultMap.put(MSG, errorMsg);
	   	isCrrossDomain(response);
	   	return resultMap;
  }
   
  
  /**
   * 联盟微信手q通过subUnionId获取推广链接
   * @author 许小宝
   * @date 2017年12月27日 下午2:36:50
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value="/getConUrl")
  @ResponseBody
  public Map<String,Object> getConUrl( HttpServletRequest request,HttpServletResponse response,String spuId,String appId ,String token){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		if( StringHelper.isNotBlank(spuId) ){
   				 GoodsSpu goodsSpu = goodsSpuService.get(spuId);
   				 if( null != goodsSpu ){
   					 //添加点击统计
   					 addClick(goodsSpu);
   					 UsersMall user =  this.getUsersByTokenAndAppId(token, appId);
   					 //用户登入后
   		   			 if( null != user ){
	   		   			 List<ShareHistory> listHistorys = shareHistoryService.listBySpuIdAndUserId(spuId, user.getId());
		   				 if( listHistorys.size()>0 ){
		   					ShareHistory shareHistory = listHistorys.get(0); 
		   				    //还是要实时的获取京东的优惠券信息
							String link = "";
							if( StringHelper.isNotBlank(shareHistory.getConUrl()) ){
								link = shareHistory.getConUrl();
							}else{
								//生成二合一链接，更新数据库
								//生成优惠券的二合一链接，更新数据库
								String tempLink = goodsSpuService.getConErheyiLink(spuId,user.getId());
								if( StringHelper.isNotBlank(tempLink) ){
									link = tempLink;
									shareHistory.setConUrl(link);
									shareHistoryService.edit(shareHistory);
								}
							}
							resultMap.put(DATA, link);
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
		   				 }else{
		   				    //添加一个分享记录
		   					String historyId = IdGen.uuid();
		   					String conUrl = goodsSpuService.getConErheyiLink(spuId,user.getId());
		   					ShareHistory shareHistory = new ShareHistory();
		   					if( StringHelper.isNotBlank(conUrl) ){
		   						shareHistory.setConUrl( conUrl );
		   					}
		   					shareHistory.setId(historyId);
		   					shareHistory.setUserId(user.getId());
		   					shareHistory.setReorder(0);
		   					shareHistory.setSpuId(goodsSpu.getId());
		   					shareHistoryService.add(shareHistory);
		   					
		   					resultMap.put(DATA, conUrl);
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
		   				 }
   		   			 }else{//用户未登入也可以进入领取红包页
	   		   			 String conLinkByDdt = goodsSpuService.getConLinkByDdt(goodsSpu.getSkuId(),goodsSpu.getConUrl(), null);
	   		   			 resultMap.put(DATA, conLinkByDdt);
	  					 errorCode = SUCCESS_ERROR_CODE;
						 errorMsg = SUCCESS_ERROR_MSG;
   		   			 }
   				 }else{
   					errorCode = LINK_NULL_ERROR_CODE;
					errorMsg = LINK_NULL_ERROR_MSG;
   				 }
   			
	   		}
	   	}catch(Exception e){
	   		errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("JdInterface", "getConUrl", e.toString(),"联盟微信手q通过subUnionId获取推广链接",e);
	   	}
	   	resultMap.put(CODE, errorCode);
	   	resultMap.put(MSG, errorMsg);
	   	isCrrossDomain(response);
	   	return resultMap;
  }
   
   /**
	 * 获取广告位
	 * 
	 * @author 许小宝
	 * @date 2017年12月22日 下午3:31:52
	 * @param request
	 * @param response
	 * @param address
	 * @return
	 */
	@RequestMapping(value = "/goods")
	@ResponseBody
	public Map<String, Object> goods(HttpServletRequest request, HttpServletResponse response,String type, String keyword, String categoryId, String categoryCode, String orderType, String goodsType) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String errorCode = PARAM_ERROR_CODE; // 缺少必填参数
		String errorMsg = PARAM_ERROR_MSG;// 缺少必填参数，返回信息

		try {
			//resultMap.put(DATA, getGoodsBySpuFromAndType(request,"jd",type));
			resultMap.put(DATA, getGoodsBySpuFromAndType(request,"jd",keyword,categoryId,categoryCode,orderType,goodsType));
			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			// 服务器异常处理
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			// 打印异常日志
			logException("YhInterface", "advert", e.toString(), "获取广告位", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response); // 跨域处理
		return resultMap;
	}
	
	/**
	 * 获取广告位
	 * 
	 * @author 许小宝
	 * @date 2017年12月22日 下午3:31:52
	 * @param request
	 * @param response
	 * @param address
	 * @return
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request, HttpServletResponse response,String type, String keyword, String categoryId, String categoryCode, String orderType, String goodsType) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String errorCode = PARAM_ERROR_CODE; // 缺少必填参数
		String errorMsg = PARAM_ERROR_MSG;// 缺少必填参数，返回信息

		try {
			//resultMap.put(DATA, getGoodsBySpuFromAndType(request,"jd",type));
			resultMap.put(DATA, getGoodsBySpuFromAndType(request,"jd",keyword,categoryId,categoryCode,orderType,goodsType));
			errorCode = SUCCESS_ERROR_CODE;
			errorMsg = SUCCESS_ERROR_MSG;
		} catch (Exception e) {
			// 服务器异常处理
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			// 打印异常日志
			logException("YhInterface", "advert", e.toString(), "获取广告位", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response); // 跨域处理
		return resultMap;
	}
}
